package com.sskj.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sskj.api.domain.Project;
import com.sskj.api.domain.ProjectMember;
import com.sskj.api.enums.ProjectMemberRoleTypeEnum;
import com.sskj.api.mapper.ProjectMapper;
import com.sskj.api.service.IProjectDeviceService;
import com.sskj.api.service.IProjectMemberService;
import com.sskj.api.service.IProjectService;
import com.sskj.api.vo.req.ProjectPageListReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.Objects;

@Service
@Slf4j
public class ProjectService extends ServiceImpl<ProjectMapper, Project> implements IProjectService {

    @Autowired
    private IProjectMemberService projectMemberService;

    @Autowired
    private IProjectDeviceService projectDeviceService;

    @Transactional
    @Override
    public void add(Project project) {
        project.setCreateTime(LocalDateTime.now());
        if(save(project)) {
            ProjectMember projectMember = new ProjectMember();
            projectMember.setProjectId(project.getId());
            projectMember.setCreateTime(LocalDateTime.now());
            projectMember.setUserId(project.getLeaderId());
            projectMember.setRoleType(ProjectMemberRoleTypeEnum.ADMIN.getRoleType());

            projectMemberService.add(projectMember);
        }
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        removeById(id);
        projectMemberService.deleteByProjectId(id);
        projectDeviceService.deleteByDeviceId(id);
    }

    @Override
    @Transactional
    public void update(Project project) {
        Project oldProject = getById(project.getId());
        if (oldProject != null) {
            project.setUpdateTime(LocalDateTime.now());
            updateById(project);

            // 更新项目负责人同步关联信息
            if (!Objects.equals(oldProject.getLeaderId(), project.getLeaderId())) {
                projectMemberService.updateAdminRole(project.getId(), project.getLeaderId());
            }
        }
    }

    @Override
    public Project detail(Long id) {
        return baseMapper.detail(id);
    }

    @Override
    public IPage<Project> pageList(ProjectPageListReq req) {
        IPage<Project> pageConfig = new Page<>(req.getPageNum(), req.getPageSize());
        return baseMapper.pageList(pageConfig, req);
    }
}
